#region Imported Namespaces
using System;
using WorFlowInterface = Workflow.NET.Interfaces;
using WorkflowNET = Workflow.NET;
using WorkFlowEngine = Workflow.NET.Engine;
using Workflow.NET.PropertyTypes;
using ibex4;
using PHSRAG.Utility;
using SysIO = System.IO;
using SysText = System.Text;
using InsightHumans = PHSRAG.Insight21.Humans;
using InsightCDS = PHSRAG.Insight21.CDS;
using InsightUtility = PHSRAG.Utility;
using InsightPolicy = PHSRAG.Insight21.Policy;
using Insight = PHSRAG.Insight21;
using InsightUtilities = PHSRAG.Insight21.InsightUtilities;
using System.Data;
using System.Data.SqlClient;
using System.Collections;
using System.Threading;
#endregion

namespace PHSRAG.Insight21.InsightWorkFlow
{
	/// <summary>
	/// This activity map handles the event from all the approval actions to provide the following functionality.
	/// 1.Manipulates the action performed by the study staff on the review step(Defines whether or not the staff is accepting his/her participation in the study)
	///	1.1 If study staff approves his/her participation, then study staff will be put to certify his participation(Study staff certification)
	///	1.2 If study staff declines his/her participation, then study staff will not be provided with the certification step.
	/// Note: Generates the certification (PDF) on the study staff approval.	  
	/// */
	/// </summary>
	public class ActivityMap : WorFlowInterface.IActivityMap
	{
		public const char DELIMITER = ',';

		public ActivityMap()
		{            
		}

		public object Parameter
		{
			get { return null; }
			set { object obj = value; }
		}

		public void BeginTransaction()
		{
		}
		public void Commit()
		{
		}
		public void RollBackTransaction()
		{
		}
		public void AddActivity(int ExecutionDetailsId, int ActivityId, object UserId, Workflow.NET.Action CurrentAction,
			Workflow.NET.Engine.Context CurrentContext, Workflow.NET.PropertyTypes.PropertyActivityCustomField.CustomFieldList CustomFields)
		{
		}
		public void UpdateActivity(int ActivityId, Workflow.NET.Engine.ActivityContext ActivityContext,
				Workflow.NET.PropertyTypes.PropertyActivityCustomField.CustomFieldList CustomFields,
				string UpdateStatus, bool CompletionMaker, string Data, object OnBehalfUser)
		{
			string actionName = ActivityContext.ActionName.ToLower();
			string incomingActionName = ActivityContext.ActionName;
			string respondingUserVar = String.Format("^{0}RespondingUser", incomingActionName);
			string protocolProcessType = ActivityContext.WorkflowContext.Contents["pptype"].Value.ToString();
			//System.Diagnostics.Debugger.Launch();
			//PDF Creation is done only in three workflows.			
			int userId;

			object insightApplicationName = ActivityContext.WorkflowContext.Contents["insightApplicationName"];
			HumansWorkFlow.InsightApplicationName = (null == insightApplicationName) ? string.Empty : ((Workflow.NET.Content)insightApplicationName).Value.ToString();

			Thread.SetData(Thread.GetNamedDataSlot("Connections"), HumansWorkFlow.Connections);
			InsightWorkFlow.HumansWorkFlow wfHumans = new InsightWorkFlow.HumansWorkFlow(new Policy.NullCachePolicy());
			int executionId = wfHumans.GetWorkflowItemId(Int32.Parse(ActivityContext.WorkflowContext.Contents["ppid"].Value.ToString()));
            if ((protocolProcessType == "PPTYPE_IR") || (protocolProcessType == "PPTYPE_AM") || (protocolProcessType == "ANIMALPPTYPE_IR") || (protocolProcessType == "ANIMALPPTYPE_TS") || (protocolProcessType == "ANIMALPPTYPE_AM") || (protocolProcessType == "ANIMALPPTYPE_TR"))
			{
                if ((actionName == "pisignoff") || (actionName == "sscertification") || (actionName == "sitepisignoff") || (actionName == "animalssscertification"))
				{
                    WorkflowNET.Resource resource = (WorkflowNET.Resource)(ActivityContext.WorkflowContext.Variables[respondingUserVar].Value);
                    userId = Int32.Parse(resource.Properties["UserID"].Value.ToString());

					if (UpdateStatus == "approved")
					{
						ActivityContext.WorkflowContext.log.LogInformation("In Update Activity PDF Creation");
						string html = string.Empty;

						if (incomingActionName != "")
						{
							string serverPath;
							DataTable dt = InsightWorkFlow.HumansWorkFlow.GetCertifiedContent(executionId, userId, actionName.ToLower());
							serverPath = dt.Rows[0].ItemArray[1].ToString();
							html = dt.Rows[0].ItemArray[0].ToString();
							if (html != null && serverPath != null)
							{
								int staffRoleType = 0;
								string exclusiveCertificationRoleTypes = string.Format("{0}{1}{2}",
																		Humans.Constants.StaffRoleType.PrincipalInvestigator.ToString("d"),
																		DELIMITER,
																		Humans.Constants.StaffRoleType.SiteResponsibleInvestigator.ToString("d"));
								switch (actionName)
								{
									case "pisignoff":
										staffRoleType = Humans.Constants.StaffRoleType.PrincipalInvestigator;
										break;
									case "sitepisignoff":
										staffRoleType = Humans.Constants.StaffRoleType.SiteResponsibleInvestigator;
										break;
								}
								CreatePDFFile(html, serverPath,
									Int32.Parse(ActivityContext.WorkflowContext.Contents["protocolid"].Value.ToString()),
									userId, Int32.Parse(ActivityContext.WorkflowContext.Contents["ppid"].Value.ToString()),
									staffRoleType, exclusiveCertificationRoleTypes);
							}
						}
					}
					InsightWorkFlow.HumansWorkFlow.RemoveCertifiedContent(executionId, userId, actionName.ToLower());
					//The following if block will support the new workflows
					if ((actionName == "sscertification" || actionName == "animalssscertification") && (UpdateStatus == "rejected"))
					{
						ValidateSSReview(ActivityContext, respondingUserVar, "rejNcssUser","");
					}
					else if ((actionName == "sscertification" || actionName == "animalssscertification") && (UpdateStatus == "approved"))
					{
                        ValidateSSReview(ActivityContext, respondingUserVar, "appNcssUser", "");
					}
				}
				else
				{
					//The following if block will support the old Workflows from being erroring out
					/*Remove the study staff from certifying as he/she has declined to participate in the study*/
					if ((actionName == "ssreview") && (UpdateStatus == "rejected"))
					{
						ValidateSSReview(ActivityContext, respondingUserVar, "rejNcssUser", "");
					}
					/*Remove the study staff from review as he/she has accepted to participate in the study*/
					else if ((actionName == "ssreview") && (UpdateStatus == "approved"))
					{
						ValidateSSReview(ActivityContext, respondingUserVar, "appNcssUser", "");
					}
                    else if ((actionName == "anciboardapproval") && (UpdateStatus == "approved"))
                    {
                        SqlParameter[] args = DataAccess.BuildSqlParameterArray("@virtualUserId", SqlDbType.Int, ActivityContext.VirtualUserId);
                        SqlDataReader reader = DataAccess.ExecuteReader(DataAccess.GetConnectionString(), "GetUserFromWorkflowActivity", args);

                        /*email helpdesk with the delimited usernames*/
                        if (reader.Read())
                        {
                            ValidateSSReview(ActivityContext, Convert.ToString(reader["UserId"]), "appNcssUser", "");
                        }
                    }
					actionName = "other";
				}
			}
		}

		public void PauseActivity(int ExecutionDetailsID, int ActivityId, Workflow.NET.Engine.Context CurrentContext, Workflow.NET.Action CurrentAction, Workflow.NET.PropertyTypes.PropertyActivityCustomField.CustomFieldList CustomFields, string Status)
		{            
		}
		public void ResumeActivity(int ExecutionDetailsID, int ActivityId, Workflow.NET.Engine.Context CurrentContext, Workflow.NET.Action CurrentAction, Workflow.NET.PropertyTypes.PropertyActivityCustomField.CustomFieldList CustomFields, string Status)
		{           
		}
		public void AbortActivity(int ExecutionDetailsID, Workflow.NET.Engine.Context CurrentContext, Workflow.NET.Action CurrentAction, Workflow.NET.PropertyTypes.PropertyActivityCustomField.CustomFieldList CustomFields, string Status)
		{           
		}
		public void TimeoutAction(int ExecutionDetailsId, Workflow.NET.Engine.ActivityContext ActivityContext, Workflow.NET.PropertyTypes.PropertyActivityCustomField.CustomFieldList CustomFields, string TimeoutType)
		{
		}
		public void ActionCompletion(int ExecutionDetailsId, Workflow.NET.Engine.ActivityContext ActivityContext, Workflow.NET.PropertyTypes.PropertyActivityCustomField.CustomFieldList CustomFields, string ActionOutput)
		{
		}
		public void ForwardActivity(int ActivityId, Workflow.NET.Engine.ActivityContext ActivityContext, Workflow.NET.PropertyTypes.PropertyActivityCustomField.CustomFieldList CustomFields, object FromResourceIdentifier, object ToResourceIdentifier)
		{
            string actionName = ActivityContext.ActionName.ToLower();
            string userType = String.Empty;
            //gets type based on the action that is happening    
            switch (actionName)
                {
                    case "sscertification":
                    case "animalssscertification":
                    case "compliancepersonapproval":
                        userType = "ncssUser";
                        break;
                    case "pisignoff":
                    case "pisignoffreview":
                    case "pi-submitter review":                   
                        userType = "piUser";
                        break;
                    case  "hrointakepersonsignoff":
                    case  "hrointake":
                    case  "hrointakeuser":
                    case  "hrointake-submitterreview":  
                    case  "hrointakesignoff":
                        userType = "hroIntakeUser";
                        break;                    
                    case "deptchairsignoff2":
                    case "deptchairsignoff":
                        userType = "deptChairUser";
                        break;
                    case "deptchairsubmitterreview":
                        userType = "deptChairDelegateUser";
                        break; 
                    case "sitedeptchairsubmitterreview":
                        userType = "siteDeptChairUser";
                        break;
                    case "siteirbchairsignoff":
                    case "siteirb-submitterreview":
                        userType = "siteIRBChairUser";
                        break;
                    case "sitepideptchairsignoff":
                        userType = "siteDeptChairUser";     //"SitePIDeptChairSignOff";
                        break;
                    case "sitepisignoff":
                    case "sitepi-submitterreview":
                        userType = "sitepiUser";
                        break;
                    case "pitosubmitter":
                    case "hrotosubmitter":
                    case "patosubmitter":
                        userType = "submitterUser";
                        break;
                    case "pasignoffreview":
                    case "pasignoff":
                        userType = "protocolAdministrator";
                        break;
                    case "ancillaryboardsignoff":
                    case "anciboardapproval":                    
                        userType = "anciBoardUser";
                        break;
                    case "ancibioboardapproval":
                        userType = "anciBioUser";
                        break;
                    case "ancichemboardapproval":
                        userType = "anciChemUser";
                        break;
                    case "anciradboardapproval":
                        userType = "anciRadUser";
                        break;
                    case "submitteractionforsracrejection":
                        userType = "rejNcssUser";
                        break;                    
                    case "sracsignoff":
                        userType = "SRACIntakeUser";
                        break;
                    case "prereviewersignoff":
                        userType = "SRACPreviewUsers";
                        break;
                    default:
                        break;
                }
            //System.Diagnostics.Debugger.Launch();
            //replaces old user with new, removes study staff and anci board members that already signed off.
            ValidateSSReview(ActivityContext, ToResourceIdentifier.ToString(), userType, FromResourceIdentifier.ToString());
            ForwardEmail(ActivityId, ActivityContext, ToResourceIdentifier, FromResourceIdentifier);
		}
        /// <summary>
        /// Send email to the person who got task forwarded to.
        /// </summary>
        /// <param name="ActivityId"></param>
        /// <param name="ActivityContext"></param>
        /// <param name="ToPerson"></param>
        /// <param name="FromPerson"></param>
        private void ForwardEmail(int ActivityId, Workflow.NET.Engine.ActivityContext ActivityContext, object ToPerson, object FromPerson)
        {
            string emailTo = String.Empty;
            string emailFrom = String.Empty;
            string body = String.Empty;
            string subject = String.Empty;

            try
            {                
                string forwardedFromPerson = ActivityContext.Resource.Properties.Name.Value.ToString();
                string protocolTitle = ActivityContext.WorkflowContext.Variables["protocolTitle"].Value.ToString();
                string protocolNumber = ActivityContext.WorkflowContext.Variables["protocolNumber"].Value.ToString();
                string piName = ActivityContext.WorkflowContext.Variables["piName"].Value.ToString();
                string executionId = ActivityContext.ExecutionId.ToString();
                string ppId = ActivityContext.WorkflowContext.Contents["ppid"].Value.ToString();
                string submissionType = ActivityContext.WorkflowContext.Variables["submissionType"].Value.ToString();
                string forwardedDate = DateTime.Now.ToString();
                string submitter = ActivityContext.WorkflowContext.Variables["submitterName"].Value.ToString();
                string activityName = string.Empty;
                string protocolType = String.Empty;
                string runEnvironment = ActivityContext.WorkflowContext.Variables["environmentAddress"].Value.ToString();
                string protocolTypeFormat = string.Empty;
                string contactInfo = string.Empty;

                emailTo = ActivityContext.Resource.Properties.Email.Value.ToString();

                if (ActivityContext.WorkflowContext.Variables["moduleType"] != null)
                    protocolType = ActivityContext.WorkflowContext.Variables["moduleType"].Value.ToString().ToLower();

                if (protocolType == "h")
                {
                    activityName = ActivityContext.CurrentAction.ActionDisplayName.ToString();
                    protocolTypeFormat = " human";
                    contactInfo = "IRB at: IRB@Partners.org";
                    emailFrom = "IRB@partners.org";
                }
                else
                {
                    activityName = ActivityContext.CurrentAction.Name.ToString();
                    protocolTypeFormat = "n animal";
                    contactInfo = "SRAC at: SRAC@Partners.org";
                    emailFrom = "SRAC@partners.org";
                }

                subject = String.Format("Forwarding a{0} research protocol submission.", protocolTypeFormat);
                string message1 = String.Format("A{0} research protocol submission has been forwarded to you and requires your review:", protocolTypeFormat);
                string link1 = String.Format("You can navigate directly to the action required by clicking the link below or by copying and pasting it into a new browser window. <br/> <a href='http://{0}/Research/WorkFlowActivityDetail.aspx?ExecutionId={1}&PPId={2}'>http://{0}/Research/WorkFlowActivityDetail.aspx?ExecutionId={1}&PPId={2}</a>", runEnvironment, executionId, ppId);
                string link2 = String.Format("This may also be accessed remotely at <a href='https://{0}/Research/WorkFlowActivityDetail.aspx?ExecutionId={1}&PPId={2}'>https://{0}/Research/WorkFlowActivityDetail.aspx?ExecutionId={1}&PPId={2}</a>", runEnvironment, executionId, ppId);
                string end = String.Format("If you have any questions, please contact the contact the {0}. {1}If you experience a technical problem, contact the Insight Helpdesk at: insighthelpdesk@partners.org.", contactInfo,"<br/><br/>");

                body = string.Format("{0}<br/><br/>Forwarded By: {1}<br/>Forwarded Date: {2}<br/>Protocol Title: {3}<br/>Protocol Number: {4}<br/>Principal Investigator: {5}<br/>Submitter: {6}<br/>Submission Type: {7}<br/>Activity Name: {8}<br/><br/>{9}<br/><br/>{10}<br/><br/>{11}",
                                            message1, forwardedFromPerson, forwardedDate, protocolTitle, protocolNumber, piName, submitter, submissionType, activityName, link1, link2, end);

                Utility.EmailNotification.SendEmail(emailFrom, emailTo, subject, body);
            }
            catch (Exception ex)
            {
                Utility.EmailNotification.SendEmail(emailFrom, emailFrom, subject, body);
                WorkflowNET.Log logger = new WorkflowNET.Log();
                logger.LogError(new System.Exception(), "Error sending Forwarding Email " + ex.Message + ": " + ex.InnerException.ToString());
                throw (ex);
            }
        }

		/// <summary>
		/// This method uses IBEX a third party component and creates PDF using serialized xml string. 
		/// XSLT transformtation is done before PDF gets generated.
		/// This PDF gets created in memory and gets inserted into database.
		/// </summary>
		/// <param name="seriliazedString">Serialized XML stream</param>
		/// <param name="serverPath">Server path to get XSLT for transformation</param>
		/// <param name="protocolId">Protocol Id for the stored procedure to store PDF</param>
		/// <param name="userId">User Id</param> 
		/// <param name="userId">Protocol Process Id</param> 
		private void CreatePDFFile(string seriliazedString, string serverPath, int protocolId,
			int userId, int protocolProcessId, int staffRoleType, string exclusiveCertificationRoleTypes)
		{
			//System.Diagnostics.Debugger.Launch();
			string xslFilePath = serverPath.Substring(0, serverPath.LastIndexOf("\\") + 1) + Utility.Settings.GetKeyValue("HumansWFXSFOFileName", "");
			SysIO.FileStream xslStream = new SysIO.FileStream(xslFilePath, SysIO.FileMode.Open, SysIO.FileAccess.Read);
			SysIO.MemoryStream pdfStream = new SysIO.MemoryStream();
			try
			{
				FODocument doc = new FODocument();

				string licLocation = System.IO.Path.Combine(serverPath, InsightHumans.Constants.Ibex.LicenseFileName);
				ibex4.licensing.Generator.LicenseFileLocation = licLocation;
				if (null == seriliazedString) return;

				using (pdfStream)
				{
					using (xslStream)
					{
						doc.generate(new SysIO.MemoryStream(SysText.Encoding.UTF8.GetBytes(seriliazedString.Substring(1))), xslStream, pdfStream, false);
					}

					InsightCDS.Document consentForm = new InsightCDS.Document(new InsightPolicy.NullCachePolicy());
					consentForm.Blob = pdfStream.ToArray();
					consentForm.Name = "ConsentForm.pdf";
					consentForm.Save(HumansWorkFlow.InsightConnection);
					InsightUtility.DataAccess.ExecuteNonQuery(HumansWorkFlow.InsightConnection, "UpdateStaffCertification", Utility.DataAccess.BuildSqlParameterArray(
						"@protocolId", SqlDbType.Int, protocolId,
						"@protocolStaffTypeId", SqlDbType.Int, staffRoleType,
						"@exclusiveCertificationRoleTypes", SqlDbType.VarChar, exclusiveCertificationRoleTypes,
						"@delimiter", SqlDbType.Char, DELIMITER,
						"@admPersonId", SqlDbType.Int, GetAdmPersonIdForLoggedInUser(protocolProcessId, userId),
						"@documentId", SqlDbType.Int, consentForm.Id));
				}
				xslStream = null;
				pdfStream = null;

			}
			catch (Exception ex)
			{
				WorkflowNET.Log logger = new WorkflowNET.Log();
				logger.LogError(new System.Exception(), "Error creating PDF in Activity.CreatePDFFile() " + ex.Message + ": " + ex.InnerException.ToString());
				throw (ex);
			}
			finally
			{
				if (xslStream != null)
					xslStream.Close();

				if (pdfStream != null)
					pdfStream.Close();
			}
		}

		/// <summary>
		/// This method gives AdmPerson Id for passed logged in user id.	
		/// </summary>		
		/// <param name="protocolId">Protocol Process Id</param>
		/// <param name="userId">User Id</param> 
		private int GetAdmPersonIdForLoggedInUser(int protocolProcessId, int userId)
		{
			int admPersonId = userId;
			try
			{
				HumansWorkFlow humansWorkflow = new HumansWorkFlow(new InsightPolicy.NullCachePolicy());
				ArrayList studyStaffList = humansWorkflow.GetStudyStaff(humansWorkflow.GetProtocolProcess(protocolProcessId));
				int staffCount = studyStaffList.Count;
				for (int count = 0; count < staffCount; ++count)
				{
					InsightHumans.StaffPerson staffPerson = (InsightHumans.StaffPerson)studyStaffList[count];
					if (staffPerson.UserId == userId)
					{
						admPersonId = staffPerson.AdmPersonId;
						break;
					}
				}
			}
			catch (Exception ex)
			{
				WorkflowNET.Log logger = new WorkflowNET.Log();
				logger.LogError(new System.Exception(), "Error getting person Id Activity.GetAdmPersonIdForLoggedInUser() " + ex.Message + ": " + ex.InnerException.ToString());
				throw (ex);
			}
			return admPersonId;
		}
		/// <summary>
		/// This method will remove the resource who had performed the action(Acknowledged)from 
		/// the studystaff list and adds the resource as rejected or approved user in workflow 
		/// context.
		/// </summary>
		/// <param name="ActivityContext">Workflow activity context</param>
		/// <param name="respondingUserVar">Studystaff responding user</param>
		/// <param name="userType">variable name to which the resource had to be added </param>
		private void ValidateSSReview(Workflow.NET.Engine.ActivityContext ActivityContext, string respondingUserVar, string userType, string previousUserVar)
		{
            //System.Diagnostics.Debugger.Launch();                
            if (ActivityContext.DisplayType != "FORWARDACTIVITY" && ActivityContext.ActionName != "AnciBoardApproval")
		    {
                ArrayList studystaffList = (ArrayList)ActivityContext.WorkflowContext.Variables["ncssUser"].Value;
                if (studystaffList != null && studystaffList.Count > 0)
                {
                    try
                    {
                        /*Get the user Id who had accepted the participation in the study */
                        int resourceUserId = Int32.Parse(((WorkflowNET.Resource)
                            (ActivityContext.WorkflowContext.Variables[respondingUserVar].Value)).
                            Properties["UserID"].Value.ToString());
                        /*Remove the user who had acknowledged(accepted) from the noncritical study staff list*/
                        studystaffList.Remove(resourceUserId);
                        /*Save the required context Variable*/
                        HumansWorkFlow humansWF = new HumansWorkFlow(new PHSRAG.Insight21.Policy.NullCachePolicy());
                        humansWF.SetContextVariables("ncssUser", studystaffList, Int32.Parse(ActivityContext.WorkflowContext.Contents["ppid"].Value.ToString()));
                        /*Save the userid to the variable(appNcssUser) to the workflow context*/
                        humansWF.SetContextVariables(userType, resourceUserId, Int32.Parse(ActivityContext.WorkflowContext.Contents["ppid"].Value.ToString()));
                        /*set the study staff count to zero when there are no study staff list(This will be used for looping though the review process)*/
                        if (studystaffList.Count == 0)
                            humansWF.SetContextVariables("ncssUsersExist", 0, Int32.Parse(ActivityContext.WorkflowContext.Contents["ppid"].Value.ToString()));
                    }
                    catch (Exception ex)
                    {
                        WorkflowNET.Log logger = new WorkflowNET.Log();
                        logger.LogError(new System.Exception(), "Error while trying to approve the review action() " + ex.Message + ": " + ex.InnerException.ToString());
                        throw new Exception("Unable to perform the requested action(approval)", ex);
                    }
                }
		    }
            else if (ActivityContext.DisplayType == "FORWARDACTIVITY")
            {
                try
                {
                    ArrayList userList = new ArrayList();
                    //gets the user Id from the corresponding user list in workflow.
                    if (userType != "protocolAdministrator")
                    {
                        userList = (ArrayList)ActivityContext.WorkflowContext.Variables[userType].Value;

                        //removes old and adds the new user to the array
                        userList.Remove(Int32.Parse(previousUserVar));
                        userList.Add(Int32.Parse(respondingUserVar));

                        //adds user array to the correct userType for the workflow.
                        HumansWorkFlow humansWF = new HumansWorkFlow(new PHSRAG.Insight21.Policy.NullCachePolicy());
                        humansWF.SetContextVariables(userType, userList, Int32.Parse(ActivityContext.WorkflowContext.Contents["ppid"].Value.ToString()));
                    }
                    else
                    {
                        int paUser = (int)ActivityContext.WorkflowContext.Variables[userType].Value;
                        HumansWorkFlow humansWF = new HumansWorkFlow(new PHSRAG.Insight21.Policy.NullCachePolicy());
                        humansWF.SetContextVariables(userType, paUser, Int32.Parse(ActivityContext.WorkflowContext.Contents["ppid"].Value.ToString()));
                    }
                }
                catch (Exception ex)
                {
                    WorkflowNET.Log logger = new WorkflowNET.Log();
                    logger.LogError(new System.Exception(), "Error while trying to approve the review action() " + ex.Message + ": " + ex.InnerException.ToString());
                    throw new Exception("Unable to perform the requested action(approval)", ex);
                }
            }
            //this logic takes out the Ancillary board user from the list if the action has been submitted by this user
            if (ActivityContext.ActionName == "AnciBoardApproval")
            {
                ArrayList anciStaffList = (ArrayList)ActivityContext.WorkflowContext.Variables["anciBoardUser"].Value;
                if ((anciStaffList != null) && (anciStaffList.Count > 0))
                {                    
                    try
                    {
                        /*Remove the user who had acknowledged(accepted) from the ancillary board staff list*/
                        anciStaffList.Remove(Convert.ToInt32(respondingUserVar));

                        HumansWorkFlow humansWF = new HumansWorkFlow(new PHSRAG.Insight21.Policy.NullCachePolicy());
                        humansWF.SetContextVariables("anciBoardUser", anciStaffList, Int32.Parse(ActivityContext.WorkflowContext.Contents["ppid"].Value.ToString()));
                    }
                    catch (Exception ex)
                    {
                        WorkflowNET.Log logger = new WorkflowNET.Log();
                        logger.LogError(new System.Exception(), "Error while trying to approve the review action() " + ex.Message + ": " + ex.InnerException.ToString());
                        throw new Exception("Unable to perform the requested action(approval)", ex);
                    }
                }
            }
		}
    }
}